package com.codingxyz.simple.nio;

import org.junit.jupiter.api.Test;

import java.nio.ByteBuffer;

/**
 * ByteBuffer
 * CharBuffer
 * ShortBuffer
 * IntBuffer
 * LongBuffer
 * FloatBuffer
 * DoubleBuffer
 *
 * 上述缓冲区操作方法几乎一致，通过allocate()获取缓冲区
 * 二、缓冲区获取数据的核心方法
 * put() 存入数据到缓冲区
 * get() 从缓冲区获取数据
 *
 * 四、缓冲区的四个核心属性
 * capacity 表示缓冲区最大存取数据的容量，一旦声明不能改变。
 * limit 界限 表示缓冲区可以操作数据的大小
 * position 位置，表示缓冲区正在操作数据的位置
 */
public class TestBuffer {

    @Test
    public void test1(){

        String str = "abcde";
        ByteBuffer buf = ByteBuffer.allocate(1024);

        System.out.println("#################初始化####################");

        System.out.println("limit "+buf.limit());
        System.out.println("position "+buf.position());
        System.out.println("capacity "+buf.capacity());

        buf.put(str.getBytes());
        System.out.println("##################put###################");

        System.out.println("limit "+buf.limit());
        System.out.println("position "+buf.position());
        System.out.println("capacity "+buf.capacity());

        /**
         * 切换到读取模式
         */
        System.out.println("##################flip#######################");
        buf.flip();

        System.out.println("limit "+buf.limit());
        System.out.println("position "+buf.position());
        System.out.println("capacity "+buf.capacity());

        System.out.println("##################get#######################");

        byte[] read = new byte[buf.limit()];
        buf.get(read);
        System.out.println(new String(read,0,read.length));

        System.out.println("limit "+buf.limit());
        System.out.println("position "+buf.position());
        System.out.println("capacity "+buf.capacity());

        /**
         * 重新读
         */
        System.out.println("##################rewind#######################");
        buf.rewind();

        System.out.println("limit "+buf.limit());
        System.out.println("position "+buf.position());
        System.out.println("capacity "+buf.capacity());
    }

    @Test
    public void test2(){

        String data = "abcde";

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(data.getBytes());
        System.out.println("position : "+buffer.position());

        buffer.flip();
        System.out.println("##################演示remark#################");
        byte[] b = new byte[3];
        buffer.get(b,0,2);
        buffer.mark();
        System.out.println("position : "+buffer.position());
        buffer.reset();
        System.out.println("position : "+buffer.position());



    }

}
